package view.dlct.truongtt.backing;


import java.util.ArrayList;
import java.util.List;


import javax.faces.application.FacesMessage;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import javax.faces.event.PhaseEvent;
import javax.faces.model.SelectItem;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.RichDialog;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.input.RichSelectOneChoice;
import oracle.adf.view.rich.component.rich.input.RichSelectOrderShuttle;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.event.DialogEvent;
import oracle.adf.view.rich.event.PopupCanceledEvent;

import oracle.jbo.Key;
import oracle.jbo.NameValuePairs;
import oracle.jbo.Row;
import oracle.jbo.domain.DBSequence;

import oracle.jbo.domain.Number;

import view.common.Utils;
import view.common.search.AdvancedSearchGroup;
import view.common.search.AdvancedSearchItem;

public class DmTruongTtBean {
    private RichPopup popupUpdate;
    private RichDialog dialogUpdate;
    private RichPopup popupDelete;
    private RichSelectOrderShuttle selectViTriHienThi;
    private RichSelectOneChoice selectNgonNgu = new RichSelectOneChoice();
    private RichSelectOneChoice searchLoaiTruongTt = new RichSelectOneChoice();
    private RichSelectOneChoice searchNgonNgu = new RichSelectOneChoice();
    private RichInputText searchTenTruong = new RichInputText();

    public DmTruongTtBean() {
    }

    public void beforePhase(PhaseEvent phaseEvent) {
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            Utils.search("DlctTruongTtView1Iterator", new ArrayList());
            resetForm();
            rollback(null);
        }
    }

    private void resetForm() {
        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asg = new AdvancedSearchGroup();
        listASG.add(asg);
        AdvancedSearchItem asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        Utils.searchadvanced("DlctNgonNguView1Iterator", listASG);
        DCIteratorBinding ngonNguView1Iterator =
            Utils.getIteratorBinding("DlctNgonNguView1Iterator");
        List<SelectItem> listSelectItem = new ArrayList();
        ngonNguView1Iterator.setRangeSize(-1);
        Row[] rows = ngonNguView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ma = (String)rows[i].getAttribute("Ma");
            String ten = (String)rows[i].getAttribute("Ten");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ma + "_" + ten);
            listSelectItem.add(si);
        }
        UISelectItems uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        searchNgonNgu.setValue(null);
        searchNgonNgu.getChildren().clear();
        searchNgonNgu.getChildren().add(uiSelectItems);

        listSelectItem = new ArrayList();
        for (Utils.ENUM_LOAI_TRUONG_TT enumViTriHienThi :
             Utils.ENUM_LOAI_TRUONG_TT.values()) {
            SelectItem si = new SelectItem();
            si.setValue(enumViTriHienThi.getId());
            si.setLabel(enumViTriHienThi.getTen());
            listSelectItem.add(si);
        }
        uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        searchLoaiTruongTt.setValue(null);
        searchLoaiTruongTt.getChildren().clear();
        searchLoaiTruongTt.getChildren().add(uiSelectItems);

        searchTenTruong.setValue(null);
    }

    public void showPopupThemMoi(ActionEvent actionEvent) {
        Utils.search("DlctTruongTtView1Iterator", new ArrayList());
        List<SelectItem> listSelectItem = new ArrayList();
        for (Utils.ENUM_VI_TRI_HIEN_THI enumViTriHienThi :
             Utils.ENUM_VI_TRI_HIEN_THI.values()) {
            SelectItem si = new SelectItem();
            si.setValue(enumViTriHienThi.getMa());
            si.setLabel(enumViTriHienThi.getTen());
            listSelectItem.add(si);
        }
        UISelectItems uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectViTriHienThi.setValue(null);
        selectViTriHienThi.getChildren().clear();
        selectViTriHienThi.getChildren().add(uiSelectItems);
        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asg = new AdvancedSearchGroup();
        listASG.add(asg);
        AdvancedSearchItem asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        Utils.searchadvanced("DlctNgonNguView1Iterator", listASG);
        DCIteratorBinding ngonNguView1Iterator =
            Utils.getIteratorBinding("DlctNgonNguView1Iterator");
        listSelectItem = new ArrayList();
        ngonNguView1Iterator.setRangeSize(-1);
        Row[] rows = ngonNguView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ma = (String)rows[i].getAttribute("Ma");
            String ten = (String)rows[i].getAttribute("Ten");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ma + "_" + ten);
            listSelectItem.add(si);
        }
        uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectNgonNgu.setValue(null);
        selectNgonNgu.getChildren().clear();
        selectNgonNgu.getChildren().add(uiSelectItems);

        dialogUpdate.setTitle((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].THEM_MOI}"));
        dialogUpdate.setAffirmativeTextAndAccessKey((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].THEM_MOI}"));

        DCIteratorBinding truongTtView1Iterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        Row row =
            truongTtView1Iterator.getViewObject().createAndInitRow(new NameValuePairs());
        truongTtView1Iterator.executeQuery();
        truongTtView1Iterator.setCurrentRowWithKey(row.getKey().toStringFormat(false));
        Utils.showPopup(popupUpdate);
    }

    public void showPopupSua(ActionEvent actionEvent) {
        DCIteratorBinding truongTtView1Iterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        if(truongTtView1Iterator.getCurrentRow()!=null){
        List<SelectItem> listSelectItem = new ArrayList();
        for (Utils.ENUM_VI_TRI_HIEN_THI enumViTriHienThi :
             Utils.ENUM_VI_TRI_HIEN_THI.values()) {
            SelectItem si = new SelectItem();
            si.setValue(enumViTriHienThi.getMa());
            si.setLabel(enumViTriHienThi.getTen());
            listSelectItem.add(si);
        }
        UISelectItems uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectViTriHienThi.getChildren().clear();
        selectViTriHienThi.getChildren().add(uiSelectItems);
        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asg = new AdvancedSearchGroup();
        listASG.add(asg);
        AdvancedSearchItem asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        Utils.searchadvanced("DlctNgonNguView1Iterator", listASG);
        DCIteratorBinding ngonNguView1Iterator =
            Utils.getIteratorBinding("DlctNgonNguView1Iterator");
        listSelectItem = new ArrayList();
        ngonNguView1Iterator.setRangeSize(-1);
        Row[] rows = ngonNguView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ma = (String)rows[i].getAttribute("Ma");
            String ten = (String)rows[i].getAttribute("Ten");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ma + "_" + ten);
            listSelectItem.add(si);
        }
        uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectNgonNgu.setValue("" +
                               truongTtView1Iterator.getCurrentRow().getAttribute("DlctNgonNguId"));
        selectNgonNgu.getChildren().clear();
        selectNgonNgu.getChildren().add(uiSelectItems);

        Number viTriHienThi =
            (Number)truongTtView1Iterator.getCurrentRow().getAttribute("ViTriHienThi");
        List<String> listSelected = new ArrayList();
        if (viTriHienThi != null) {
            int viTri = viTriHienThi.intValue();
            for (Utils.ENUM_VI_TRI_HIEN_THI enumViTriHienThi :
                 Utils.ENUM_VI_TRI_HIEN_THI.values()) {
                if ((viTri & enumViTriHienThi.getId()) ==
                    enumViTriHienThi.getId()) {
                    listSelected.add(enumViTriHienThi.getMa());
                }
            }
        }
        selectViTriHienThi.setValue(listSelected);
        dialogUpdate.setTitle((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].CAP_NHAT}"));
        dialogUpdate.setAffirmativeTextAndAccessKey((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].CAP_NHAT}"));
        Utils.showPopup(popupUpdate);        }else{
            String errorString =
                Utils.getResourceBundle("CHON_BAN_GHI_DE_THAO_TAC");
            FacesContext.getCurrentInstance().addMessage(null,
                                                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                          errorString,
                                                                          errorString));
        }
    }

    public void showPopupXoa(ActionEvent actionEvent) {
        DCIteratorBinding truongTtView1Iterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        if(truongTtView1Iterator.getCurrentRow()!=null){
        Utils.showPopup(popupDelete);
        }else{
            String errorString =
                Utils.getResourceBundle("CHON_BAN_GHI_DE_THAO_TAC");
            FacesContext.getCurrentInstance().addMessage(null,
                                                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                          errorString,
                                                                          errorString));
        }
    }

    public void timKiem(ActionEvent actionEvent) {
        List<AdvancedSearchGroup> listASG = new ArrayList();
        Object valObject = searchTenTruong.getValue();
        if (valObject != null && valObject.toString().isEmpty() == false) {
            try {
                String valString = (String)valObject;
                valString = valString.toUpperCase().trim();
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asi = new AdvancedSearchItem();
                asg.getListChildren().add(asi);
                asi.setItemName("TenTruong");
                asi.setRequired(true);
                asi.setUpperColumns(true);
                asi.setRequired(true);
                asi.setOperator(AdvancedSearchItem.OPER_CONTAINS);
                asi.getListValue().add(valString);
            } catch (Exception e) {
                e.printStackTrace();
                String errorString =
                    Utils.getResourceBundle("GIA_TRI_KHONG_HOP_LE");
                FacesContext.getCurrentInstance().addMessage(searchTenTruong.getClientId(FacesContext.getCurrentInstance()),
                                                             new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                              errorString,
                                                                              errorString));
            }
        }
        valObject = searchLoaiTruongTt.getValue();
        if (valObject != null && valObject.toString().isEmpty() == false) {
            try {
                Number valNumber = new Number(valObject);
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asi = new AdvancedSearchItem();
                asg.getListChildren().add(asi);
                asi.setItemName("DlctLoaiTruongTt");
                asi.setRequired(true);
                asi.getListValue().add(valNumber);
            } catch (Exception e) {
                e.printStackTrace();
                String errorString =
                    Utils.getResourceBundle("GIA_TRI_KHONG_HOP_LE");
                FacesContext.getCurrentInstance().addMessage(searchLoaiTruongTt.getClientId(FacesContext.getCurrentInstance()),
                                                             new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                              errorString,
                                                                              errorString));
            }
        }
        valObject = searchNgonNgu.getValue();
        if (valObject != null && valObject.toString().isEmpty() == false) {
            try {
                Number valNumber = new Number(valObject);
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asi = new AdvancedSearchItem();
                asg.getListChildren().add(asi);
                asi.setItemName("DlctNgonNguId");
                asi.setRequired(true);
                asi.getListValue().add(valNumber);
            } catch (Exception e) {
                e.printStackTrace();
                String errorString =
                    Utils.getResourceBundle("GIA_TRI_KHONG_HOP_LE");
                FacesContext.getCurrentInstance().addMessage(searchLoaiTruongTt.getClientId(FacesContext.getCurrentInstance()),
                                                             new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                              errorString,
                                                                              errorString));
            }
        }
        Utils.searchadvanced("DlctTruongTtView1Iterator", listASG);
    }

    public void rollback(PopupCanceledEvent popupCanceledEvent) {
        DCIteratorBinding truongTtView1Iterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        truongTtView1Iterator.getDataControl().getApplicationModule().getTransaction().rollback();
        String rowKey = null;
        if (truongTtView1Iterator.getCurrentRow() != null)
            rowKey =
                    truongTtView1Iterator.getCurrentRow().getKey().toStringFormat(false);
        timKiem(null);
        if (rowKey != null)
            truongTtView1Iterator.setCurrentRowWithKey(rowKey);
    }

    public void commit(DialogEvent dialogEvent) {
        List<String> listSelected =
            (List<String>)selectViTriHienThi.getValue();
        int viTriHienThi = 0;
        if (listSelected != null) {
            for (Utils.ENUM_VI_TRI_HIEN_THI enumViTriHienThi :
                 Utils.ENUM_VI_TRI_HIEN_THI.values()) {
                if (listSelected.contains(enumViTriHienThi.getMa())) {
                    viTriHienThi = viTriHienThi | enumViTriHienThi.getId();
                }
            }
        }
        DCIteratorBinding truongTtView1Iterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        truongTtView1Iterator.getCurrentRow().setAttribute("ViTriHienThi",
                                                           new Number(viTriHienThi));
        try {
            truongTtView1Iterator.getCurrentRow().setAttribute("DlctNgonNguId",
                                                               new Number(selectNgonNgu.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<String> listTruongTt = new ArrayList();
        listTruongTt.add("TenTruong");
        listTruongTt.add("Expression");
        for (String tenField : listTruongTt) {
            String value =
                (String)truongTtView1Iterator.getCurrentRow().getAttribute(tenField);
            if (value != null) {
                truongTtView1Iterator.getCurrentRow().setAttribute(tenField,
                                                                   value.trim());
            }
        }
        truongTtView1Iterator.getDataControl().getApplicationModule().getTransaction().commit();
        String rowKey =
            truongTtView1Iterator.getCurrentRow().getKey().toStringFormat(false);
        timKiem(null);
        truongTtView1Iterator.setCurrentRowWithKey(rowKey);
    }

    public void delete(DialogEvent dialogEvent) {
        try {
            DCIteratorBinding truongTtView1Iterator =
                Utils.getIteratorBinding("DlctTruongTtView1Iterator");
            List<AdvancedSearchGroup> listASG = new ArrayList();
            AdvancedSearchGroup asg = new AdvancedSearchGroup();
            listASG.add(asg);
            AdvancedSearchItem asi = new AdvancedSearchItem();
            asg.getListChildren().add(asi);
            asi.setItemName("DlctTruongTtId");
            asi.setRequired(true);
            asi.getListValue().add(0,
                                   ((DBSequence)truongTtView1Iterator.getCurrentRow().getAttribute("Id")).getSequenceNumber());

            List<String> listIter = new ArrayList();
            listIter.add("DlctGtBcTtViewIterator");
            listIter.add("DlctGtCbttTtViewIterator");
            listIter.add("DlctGtDvTtViewIterator");
            listIter.add("DlctGtKtvTtViewIterator");
            listIter.add("DlctGtLckTtViewIterator");
            listIter.add("DlctGtSgdTtViewIterator");
            for (String iter : listIter) {
                Utils.searchadvanced(iter, listASG);
                DCIteratorBinding iterator = Utils.getIteratorBinding(iter);
                iterator.setRangeSize(-1);
                Row[] rows = iterator.getAllRowsInRange();
                if (rows == null) {
                    rows = new Row[] { };
                }
                List<String> listDelete = new ArrayList();
                for (int i = 0; i < rows.length; i++) {
                    Key key = rows[i].getKey();
                    listDelete.add(key.toStringFormat(false));
                }
                for (String key : listDelete) {
                    iterator.removeRowWithKey(key);
                }
            }
            truongTtView1Iterator.removeCurrentRow();
            truongTtView1Iterator.getDataControl().getApplicationModule().getTransaction().commit();
            truongTtView1Iterator.executeQuery();
        } catch (Exception e) {
            String errorString =
                Utils.getResourceBundle("CON_BAN_GHI_LIEN_QUAN");
            FacesContext.getCurrentInstance().addMessage(dialogEvent.getComponent().getClientId(FacesContext.getCurrentInstance()),
                                                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                          errorString,
                                                                          errorString));
            e.printStackTrace();
        }
    }

    public void setPopupUpdate(RichPopup popupUpdate) {
        this.popupUpdate = popupUpdate;
    }

    public RichPopup getPopupUpdate() {
        return popupUpdate;
    }

    public void setDialogUpdate(RichDialog dialogUpdate) {
        this.dialogUpdate = dialogUpdate;
    }

    public RichDialog getDialogUpdate() {
        return dialogUpdate;
    }

    public void setPopupDelete(RichPopup popupDelete) {
        this.popupDelete = popupDelete;
    }

    public RichPopup getPopupDelete() {
        return popupDelete;
    }

    public void setSelectViTriHienThi(RichSelectOrderShuttle selectViTriHienThi) {
        this.selectViTriHienThi = selectViTriHienThi;
    }

    public RichSelectOrderShuttle getSelectViTriHienThi() {
        return selectViTriHienThi;
    }

    public void setSearchNgonNgu(RichSelectOneChoice searchNgonNgu) {
        this.searchNgonNgu = searchNgonNgu;
    }

    public RichSelectOneChoice getSearchNgonNgu() {
        return searchNgonNgu;
    }

    public void setSearchTenTruong(RichInputText searchTenTruong) {
        this.searchTenTruong = searchTenTruong;
    }

    public RichInputText getSearchTenTruong() {
        return searchTenTruong;
    }

    public void setSelectNgonNgu(RichSelectOneChoice selectNgonNgu) {
        this.selectNgonNgu = selectNgonNgu;
    }

    public RichSelectOneChoice getSelectNgonNgu() {
        return selectNgonNgu;
    }

    public void setSearchLoaiTruongTt(RichSelectOneChoice searchLoaiTruongTt) {
        this.searchLoaiTruongTt = searchLoaiTruongTt;
    }

    public RichSelectOneChoice getSearchLoaiTruongTt() {
        return searchLoaiTruongTt;
    }
}
